<script setup lang="ts">
import request from "@/utils/request.ts";
import { reactive } from "vue";
import {ElMessage, type UploadProps} from "element-plus";
//1、定义向父组件提交数据的事件，事件名称为sendParent
// const emit = defineEmits(["sendParent"]);
const data = reactive({
  avatar: "",
  username: "",
  user: JSON.parse(localStorage.getItem("code_user") || "{}"),
  dialogVisible: false,
  dialogVisible2: false,
});
// 初始化：回显本地存储的用户信息（头像+姓名）
const initUserInfo = () => {
  data.avatar = data.user.avatar || ""
  data.username = data.user.username || ""
};
initUserInfo();
const loginout = () => {
  localStorage.removeItem("code_user");
  location.href = "/login";
}
const updateAvatar = async () => {
  if (!data.user.userid) {
    ElMessage.error("用户信息异常，请重新登录");
    loginout();
    return;
  }
  const userData = {
    userid: data.user.userid,
    avatar: data.avatar,
  }
  request.put('/updateUser', userData).then((res) => {
      if (res.status === '200') {
        ElMessage.success("头像更换成功");
        const updatedUser = {...data.user, avatar: data.avatar};
        localStorage.setItem("code_user", JSON.stringify(updatedUser));
        data.user = updatedUser;
        data.dialogVisible = false;
      } else {
        ElMessage.error(res.msg);
      }
    })
}
const updateUsername = async () => {
  if (!data.user.userid) {
    ElMessage.error("用户信息异常，请重新登录");
    loginout();
    return;
  }
  const userData = {
    userid: data.user.userid,
    username: data.username // 只包含用户名字段
  }
  request.put('/updateUsername', userData).then((res) => {
    if (res.status === '200') {
      ElMessage.success("姓名修改成功");
      // 更新本地存储和页面状态
      const updatedUser = { ...data.user, username: data.username };
      localStorage.setItem("code_user", JSON.stringify(updatedUser));
      data.user = updatedUser// 同步更新响应式数据
      data.dialogVisible2 = false
      // emit("sendParent", updatedUser); // 通知父组件
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  data.avatar = response.data; // 保存服务器返回的头像路径
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const isImage = rawFile.type === "image/jpeg" || rawFile.type === "image/png";
  if (!isImage) {
    ElMessage.error("头像必须是JPG或PNG格式！");
    return false;
  }
  const isLt2MB = rawFile.size / 1024 / 1024 < 2;
  if (!isLt2MB) {
    ElMessage.error("头像大小不能超过2MB！");
    return false;
  }
  return true;
};
const confirmAvatarUpdate = () => {
  if (!data.avatar) {
    ElMessage.warning("请先上传头像")
    return;
  }
  updateAvatar()
};
const updateUserUsername = () => {
  updateUsername()
};
</script>
<template>
  <div class="user-setting">
      <div class="avatar-preview">
        <img
            v-if="data.avatar"
            :src="`http://localhost:8080${data.avatar}`"
            alt="当前头像"
            @click="data.dialogVisible=true"
        >
        <el-icon v-else class="default-avatar"><Plus /></el-icon>
      </div>
    <el-dialog
        v-model="data.dialogVisible"
        title="上传头像"
        width="350px"
        destroy-on-close
        :close-on-click-modal="false"
    >
    <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        style="margin-bottom: 20px;"
    >
      <div class="upload-area">
        <img
            v-if="data.avatar"
            :src="`http://localhost:8080${data.avatar}`"
            alt="头像预览"
        >
        <el-icon v-else class="upload-icon"><Plus /></el-icon>
      </div>
    </el-upload>
    <div class="dialog-footer" >
      <el-button @click="data.dialogVisible = false">取消</el-button>
      <el-button
          @click="confirmAvatarUpdate"
          type="primary"
      >
        确认修改头像
      </el-button>
    </div>
    </el-dialog>
      <span class="username-span">{{data.username}}</span><br>
      <button class="bt_x" @click="data.dialogVisible2=true" maxlength="4">
        修改姓名
      </button>
    <el-dialog
        v-model="data.dialogVisible2"
        title="修改姓名"
        width="350px"
        destroy-on-close
        :close-on-click-modal="false"
    >
      <el-input
          v-model="data.username"
          placeholder="请输入用户名（1-4位）"
          :maxlength="4"
          style="width: 200px;display: flex;margin-left: 60px;font-size: 18px;margin-bottom: 20px"
      ></el-input>
      <div class="dialog-footer" style="text-align: center;">
        <el-button @click="data.dialogVisible2 = false">取消</el-button>
        <el-button
            @click="updateUserUsername"
            type="primary"
        >
          确认修改名称
        </el-button>
      </div>
    </el-dialog>
    <button class="bt_t" @click="loginout">
      退出登录
    </button>
  </div>
</template>
<style scoped>
.user-setting {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  width: 100%;
}
/* 当前头像预览样式 */
.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #f0f2f5;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f7f8fa;
}
.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例，避免拉伸 */
}
.default-avatar {
  font-size: 28px;
  color: #c0c4cc;
}
/* 弹窗内上传区域样式 */
.upload-area {
  width: 180px;
  height: 180px;
  border-radius: 50%;
  margin-left: 75px;
  overflow: hidden;
  border: 2px dashed #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f9fafc;
  cursor: pointer;
  transition: border-color 0.3s;
}
.upload-area:hover {
  border-color: #409eff; /*  hover时高亮边框，提示可点击 */
}
.upload-area img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.upload-icon {
  font-size: 36px;
  color: #909399;
}
.username-span{
  margin-top: 10px;
  font-size: 22px;
  font-weight: bold;
}
/* 弹窗底部按钮间距 */
.dialog-footer button {
  margin: 0 35px;
}
.bt_x,.bt_t{
  width: 98%;
  height: 50px;
  margin-bottom: 10px;
  border: 0;
  font-size: 14px;
  font-weight: bold;
  color: #0f0f0f;
}
.bt_x{
  background: rgba(197, 201, 198, 0.95);
}
.bt_t{
  background: rgba(162, 6, 6, 0.86);
}

</style>